package com.example.opengldemo.jbulletJava;
import javax.vecmath.Quat4f;
import javax.vecmath.Vector3f;
import com.bulletphysics.collision.shapes.CollisionShape;
import com.bulletphysics.dynamics.DiscreteDynamicsWorld;
import com.bulletphysics.dynamics.RigidBody;
import com.bulletphysics.dynamics.RigidBodyConstructionInfo;
import com.bulletphysics.linearmath.DefaultMotionState;
import com.bulletphysics.linearmath.Transform;
import com.example.opengldemo.util.MatrixState;

public class LoadRigidBody extends BNThing
{
	ObjectVertexTexcoorsNormal lovo;
	RigidBody body;
	int mProgram;
	public LoadRigidBody(int mProgram,float mass,ObjectVertexTexcoorsNormal lovo,float cx,float cy,float cz,DiscreteDynamicsWorld dynamicsWorld)
	{
		this.lovo=lovo;
		this.mProgram=mProgram;
		CollisionShape colShape=lovo.loadShape;
		boolean isDynamic = (mass != 0f);
		Vector3f localInertia = new Vector3f(0f, 0f, 0f);
		if (isDynamic) {
			colShape.calculateLocalInertia(mass, localInertia);
		}
		Transform startTransform = new Transform();
		startTransform.setIdentity();
		startTransform.origin.set(new Vector3f(cx, cy, cz));

		DefaultMotionState myMotionState = new DefaultMotionState(startTransform);		

		RigidBodyConstructionInfo cInfo = new RigidBodyConstructionInfo
									(mass, myMotionState, colShape, localInertia);
		body = new RigidBody(cInfo);
		body.setRestitution(0.4f);
		body.setFriction(0.8f);
		dynamicsWorld.addRigidBody(body);
	}

	public void drawSelf(int[] texId)
	{
		lovo.initShader(mProgram);
		MatrixState.pushMatrix();

		Transform trans = body.getMotionState().getWorldTransform(new Transform());

		MatrixState.translate(trans.origin.x,trans.origin.y, trans.origin.z);
		Quat4f ro=trans.getRotation(new Quat4f());
		if(ro.x!=0||ro.y!=0||ro.z!=0)
		{
			float[] fa=SYSUtil.fromSYStoAXYZ(ro);
			MatrixState.rotate(fa[0], fa[1], fa[2], fa[3]);
		}
		lovo.drawSelf(texId[0]);
		MatrixState.popMatrix();
	}
}
